package com.tedu.weibo.common.exception;

import com.tedu.weibo.common.result.JsonResult;
import com.tedu.weibo.common.result.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

//@ControllerAdvice
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler
//    @RequestBody
    public JsonResult doHandleRuntimeException(RuntimeException e){
        log.error(e.getMessage(),e);
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }
    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException e){
        String message = e.getFieldError().getDefaultMessage();
        log.error(message,e);
        return new JsonResult(StatusCode.VALUEDATE_ERROR,message);
    }

    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException e){
        log.error(e.getMessage(),e);
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e){
        String message = e.getMessage();
        message=message.substring(message.indexOf(":")+1).trim();
        log.error(message,e);
        return new JsonResult(StatusCode.VALUEDATE_ERROR,message);
    }



    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable e){
        log.error(e.getMessage(),e);
        return new JsonResult(StatusCode.UNKNOWN_ERROR);
    }


}
